package com.heima.user.service.impl;

import com.heima.common.constants.user.UserRelationConstants;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;

import com.heima.model.common.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.dtos.UserRelationDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.service.ApUserRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class ApUserRelationServiceImpl implements ApUserRelationService {
    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public ResponseResult follow(UserRelationDTO dto) {
        // 1. 校验参数    authorApUserId   必须登录   operation 0  1
        ApUser user1 = AppThreadLocalUtils.getUser();
        if (user1 == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "请先登录");
        }
        Integer loginUserId = user1.getId();
        Integer authorUserId = dto.getAuthorApUserId();
        Short operation = dto.getOperation();
        if (operation.intValue() == 0) {
            Double score = redisTemplate.opsForZSet().score(UserRelationConstants.FOLLOW_LIST + loginUserId, String.valueOf(authorUserId));
            if (score != null) {
                CustException.cust(AppHttpCodeEnum.DATA_EXIST, "请勿重复关注");
            }
            if (loginUserId.equals(authorUserId)) {
                CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "请勿自己关注自己");
            }
            redisTemplate.opsForZSet().add(
                    UserRelationConstants.FOLLOW_LIST + loginUserId,
                    String.valueOf(authorUserId),
                    System.currentTimeMillis()
            );

            redisTemplate.opsForZSet().add(
                    UserRelationConstants.FANS_LIST + authorUserId,
                    String.valueOf(loginUserId),
                    System.currentTimeMillis()
            );
        } else {
            redisTemplate.opsForZSet().remove(UserRelationConstants.FOLLOW_LIST + loginUserId, String.valueOf(authorUserId));
            redisTemplate.opsForZSet().remove(UserRelationConstants.FANS_LIST + authorUserId, String.valueOf(loginUserId));
        }

        return ResponseResult.okResult();
    }
}